package com.px.framework.mqtt;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @author WRJ
 * @description mqtt订阅
 * @date 2024-08
 */
@Component
@Configuration
@ConfigurationProperties("mqtt")
public class MqttConfiguration {
    @Autowired
    private MqttCustomerClient mqttCustomerClient;

    private String host;
    private String clientid;
    private String username;
    private String password;
    private String topic;
    private int timeout;
    private int keepalive;

    public void setMqttCustomerClient(MqttCustomerClient mqttCustomerClient) {
        this.mqttCustomerClient = mqttCustomerClient;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getClientid() {
        return clientid;
    }

    public void setClientid(String clientid) {
        this.clientid = clientid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public int getKeepalive() {
        return keepalive;
    }

    public void setKeepalive(int keepalive) {
        this.keepalive = keepalive;
    }

    @Bean
    public MqttCustomerClient getMqttCustomerClient() {
        mqttCustomerClient.connect(host, clientid, username, password, timeout,keepalive);
        String[] topics = topic.split(",");
        for (String t : topics) {
            mqttCustomerClient.subscribe(t);
        }
        return mqttCustomerClient;
    }

    public void reconnection() {
        if (mqttCustomerClient.getClient() == null || !mqttCustomerClient.getClient().isConnected()) {
            mqttCustomerClient.connect(host, clientid, username, password, timeout,keepalive);
            String[] topics = topic.split(",");
            for (String t : topics) {
                mqttCustomerClient.subscribe(t);
            }
        }
    }

}